<template>
  <div class="venue-list">
    <div class="header">
      <h1 class="page-title">场地管理</h1>
      <el-button type="primary" @click="createVenue">
        <el-icon><Plus /></el-icon>
        <span>新建场地</span>
      </el-button>
    </div>

    <!-- 搜索和筛选 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="关键词">
          <el-input
            v-model="searchForm.keyword"
            placeholder="搜索场地名称"
            clearable
            style="width: 200px"
          />
        </el-form-item>

        <el-form-item label="城市">
          <el-input
            v-model="searchForm.city"
            placeholder="城市"
            clearable
            style="width: 150px"
          />
        </el-form-item>

        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="全部" clearable style="width: 150px">
            <el-option label="营业中" value="active" />
            <el-option label="暂停营业" value="inactive" />
            <el-option label="维护中" value="maintenance" />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            <span>搜索</span>
          </el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 场地列表 -->
    <el-card class="table-card">
      <el-table
        :data="venueList"
        v-loading="loading"
        stripe
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80" />
        
        <el-table-column label="场地信息" min-width="300">
          <template #default="{ row }">
            <div class="venue-info">
              <el-image 
                :src="row.coverImage || '/default-venue.png'" 
                fit="cover"
                class="cover-image"
              />
              <div class="venue-detail">
                <div class="name">{{ row.name }}</div>
                <div class="address">
                  <el-icon><Location /></el-icon>
                  <span>{{ row.city }} {{ row.district }}</span>
                </div>
              </div>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="类型" width="120">
          <template #default="{ row }">
            <el-tag>{{ row.category || '其他' }}</el-tag>
          </template>
        </el-table-column>

        <el-table-column label="容量" width="100">
          <template #default="{ row }">
            {{ row.capacity || 0 }}人
          </template>
        </el-table-column>

        <el-table-column label="评分" width="120">
          <template #default="{ row }">
            <el-rate 
              v-model="row.rating" 
              disabled 
              show-score 
              text-color="#ff9900" 
              score-template="{value}"
            />
          </template>
        </el-table-column>

        <el-table-column prop="totalBookings" label="预订次数" width="100" />

        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="认证" width="80">
          <template #default="{ row }">
            <el-tag v-if="row.isVerified" type="success" size="small">已认证</el-tag>
            <el-tag v-else type="info" size="small">未认证</el-tag>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="250" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" size="small" @click="viewDetail(row.id)">
              查看
            </el-button>
            <el-button link type="warning" size="small" @click="editVenue(row.id)">
              编辑
            </el-button>
            <el-dropdown @command="(cmd) => handleCommand(cmd, row)">
              <el-button link type="info" size="small">
                更多<el-icon class="el-icon--right"><arrow-down /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="updateStatus">更新状态</el-dropdown-item>
                  <el-dropdown-item command="delete" divided>删除</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.page_size"
        :total="pagination.total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="loadVenues"
        @current-change="loadVenues"
        class="pagination"
      />
    </el-card>

    <!-- 更新状态对话框 -->
    <el-dialog v-model="statusDialogVisible" title="更新场地状态" width="400px">
      <el-form :model="statusForm" label-width="80px">
        <el-form-item label="状态">
          <el-select v-model="statusForm.status" style="width: 100%">
            <el-option label="营业中" value="active" />
            <el-option label="暂停营业" value="inactive" />
            <el-option label="维护中" value="maintenance" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="statusDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmUpdateStatus">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { venueApi } from '@/api/venue'
import dayjs from 'dayjs'

const router = useRouter()

const loading = ref(false)
const venueList = ref([])
const statusDialogVisible = ref(false)
const currentVenue = ref(null)

const searchForm = reactive({
  keyword: '',
  city: '',
  status: ''
})

const statusForm = reactive({
  status: ''
})

const pagination = reactive({
  page: 1,
  page_size: 20,
  total: 0
})

onMounted(() => {
  loadVenues()
})

const loadVenues = async () => {
  loading.value = true

  try {
    const params = {
      page: pagination.page,
      page_size: pagination.page_size,
      ...searchForm
    }

    const data = await venueApi.getVenueList(params)
    
    venueList.value = data.items || []
    pagination.total = data.total || 0
  } catch (error) {
    console.error('加载场地列表失败:', error)
    ElMessage.error('加载场地列表失败')
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  pagination.page = 1
  loadVenues()
}

const handleReset = () => {
  searchForm.keyword = ''
  searchForm.city = ''
  searchForm.status = ''
  handleSearch()
}

const createVenue = () => {
  router.push('/venues/create')
}

const viewDetail = (id) => {
  router.push(`/venues/${id}`)
}

const editVenue = (id) => {
  router.push(`/venues/edit/${id}`)
}

const handleCommand = (command, venue) => {
  currentVenue.value = venue
  switch (command) {
    case 'updateStatus':
      statusForm.status = venue.status
      statusDialogVisible.value = true
      break
    case 'delete':
      deleteVenue(venue.id)
      break
  }
}

const confirmUpdateStatus = async () => {
  try {
    await venueApi.updateVenueStatus(currentVenue.value.id, statusForm.status)
    ElMessage.success('状态更新成功')
    statusDialogVisible.value = false
    loadVenues()
  } catch (error) {
    console.error('更新失败:', error)
  }
}

const deleteVenue = (id) => {
  ElMessageBox.confirm('确定要删除该场地吗？此操作不可恢复', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'error'
  }).then(async () => {
    try {
      await venueApi.deleteVenue(id)
      ElMessage.success('删除成功')
      loadVenues()
    } catch (error) {
      console.error('删除失败:', error)
    }
  }).catch(() => {})
}

const getStatusType = (status) => {
  const types = {
    active: 'success',
    inactive: 'warning',
    maintenance: 'info'
  }
  return types[status] || ''
}

const getStatusText = (status) => {
  const texts = {
    active: '营业中',
    inactive: '暂停营业',
    maintenance: '维护中'
  }
  return texts[status] || status
}
</script>

<style scoped>
.venue-list {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-title {
  font-size: 24px;
  color: #303133;
  margin: 0;
}

.search-card {
  margin-bottom: 20px;
}

.table-card {
  border-radius: 8px;
}

.venue-info {
  display: flex;
  gap: 12px;
  align-items: center;
}

.cover-image {
  width: 80px;
  height: 60px;
  border-radius: 4px;
  flex-shrink: 0;
}

.venue-detail {
  flex: 1;
  min-width: 0;
}

.name {
  font-weight: 600;
  color: #303133;
  margin-bottom: 4px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.address {
  font-size: 12px;
  color: #909399;
  display: flex;
  align-items: center;
  gap: 4px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>

